package com.face.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.face.common.pojo.FaceResult;
import com.face.common.utils.ExceptionUtil;
import com.face.mapper.SysPermissionMapper;
import com.face.mapper.TeacherPermissionsMapper;
import com.face.pojo.MenuAndPermission;
import com.face.pojo.SysPermission;
import com.face.pojo.SysPermissionExample;
import com.face.pojo.SysPermissionExample.Criteria;
import com.face.pojo.TeacherPermissions;
import com.face.service.SysPermissionService;

@Service
public class SysPermissionServiceImpl implements SysPermissionService{

	@Autowired
	private SysPermissionMapper permissionMapper;
	
	@Autowired
	private TeacherPermissionsMapper teacherPermissionsMapper;
	
	@Override
	public List<MenuAndPermission> getPermissionAndMenu(){
		try {
			SysPermissionExample example=new SysPermissionExample();
			Criteria criteria = example.createCriteria();
			criteria.andTypeEqualTo("menu");
			List<SysPermission> list = permissionMapper.selectByExample(example);
			List<MenuAndPermission> result=new ArrayList<>();
			for(SysPermission sys:list){
				MenuAndPermission menuAndPermission=new MenuAndPermission();
				List<SysPermission> permissions = getPermissions(sys.getId());
				menuAndPermission.setMenu(sys);
				menuAndPermission.setPermissions(permissions);
				result.add(menuAndPermission);
			}
			
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public List<SysPermission> getPermissions(Long id){
		try {
			SysPermissionExample example=new SysPermissionExample();
			Criteria criteria = example.createCriteria();
			criteria.andParentidEqualTo(id);
			List<SysPermission> list = permissionMapper.selectByExample(example);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	@Override
	public FaceResult insertPermissions(Integer teacherId,Long[] permissions) {
		try {
			for(Long permission:permissions){
				TeacherPermissions teacherPermissions=new TeacherPermissions();
				teacherPermissions.setId(null);
				teacherPermissions.setTeacherId(teacherId);
				teacherPermissions.setSysPermissionId(permission);
				teacherPermissionsMapper.insert(teacherPermissions);
			}
			return FaceResult.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return FaceResult.build(500,ExceptionUtil.getStackTrace(e));
		}
		
		
		
	}

}
